package com.tony.easymvc.core;

import java.util.List;

import com.google.common.collect.Lists;
import com.tony.easymvc.core.bean.ConfigModel;
import com.tony.easymvc.core.bean.ModuleConfig;
import com.tony.easymvc.core.bean.ModuleModel;
import com.tony.easymvc.core.bean.ProjectModel;
import com.tony.easymvc.po.ProjectBiz;

public class ModuleBuilder {

	public static void build(ConfigModel config) {
		// 基础包
		List<ModuleModel> mmsBase = createModule(config);
		// 业务包
		List<ModuleModel> bizmms = createLoopModule(config, ModuleConfig.BIZ);
		// dal包
		List<ModuleModel> dals = createLoopModule(config, ModuleConfig.DAL);
		// 数据源包
		List<ModuleModel> datasources = createLoopModule(config, ModuleConfig.DS);

		addModules(config, mmsBase);
		addModules(config, bizmms);
		addModules(config, dals);
		addModules(config, datasources);
	}

	private static void addModules(ConfigModel config, List<ModuleModel> mmsBase) {
		for (int i = 0; i < mmsBase.size(); i++) {
			config.addModules(mmsBase.get(i));
		}
	}

	private static List<ModuleModel> createLoopModule(ConfigModel config, ModuleConfig type) {
		List<ProjectBiz> projectBiz = config.getProject().getProjectContext().getProjectBizs();
		List<ModuleModel> items = Lists.newArrayList();
		for (int i = 0; i < projectBiz.size(); i++) {
			ProjectBiz pb = projectBiz.get(i);
			ModuleModel mmodel = createLoopModel(pb, config, type);
			items.add(mmodel);
		}
		return items;
	}

	private static ModuleModel createLoopModel(ProjectBiz pb, ConfigModel config, ModuleConfig type) {
		ModuleModel mmodel = new ModuleModel();
		mmodel.setArtifactId(config.getProject().getPix() + type.getModuleNames() + pb.getBizName());
		mmodel.setPackageing("jar");
		mmodel.setPath(config.getParentProjectPath() + "/" + mmodel.getArtifactId());
		mmodel.setBizName(pb.getBizName());
		mmodel.setTmplName("default/" + type.getModuleNames() + ".tmpl");
		mmodel.setType(type);
		return mmodel;
	}

	private static ModuleModel createModuleModel(ModuleConfig mconfig, ConfigModel config) {
		ProjectModel project = config.getProject();
		ModuleModel mm = new ModuleModel();
		mm.setArtifactId(project.getPix() + "_" + mconfig.getModuleNames());
		mm.setPackageing(mconfig.getPackageing());
		mm.setPath(config.getParentProjectPath() + "/" + mm.getArtifactId());
		mm.setTmplName(mconfig.getTmplName());
		mm.setType(mconfig);
		return mm;
	}

	private static List<ModuleModel> createModule(ConfigModel config) {
		ModuleConfig[] mconfigs = ModuleConfig.values();
		List<ModuleModel> item = Lists.newArrayListWithCapacity(mconfigs.length);
		for (int i = 0; i < mconfigs.length; i++) {
			ModuleConfig mconfig = mconfigs[i];
			if (mconfig.isBase()) {
				item.add(createModuleModel(mconfig, config));
			}
		}
		return item;
	}
}
